<template>
	<xn-form-container :title="title" width="1000" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-row style="margin-bottom: 20px">
			<a-col :span="12">
				<div>
					<span style="margin-right: 12px">合作商主体:</span>
					<a-radio-group v-model:value="supplierEntity">
						<a-radio value="1">公司</a-radio>
						<a-radio value="2">个人</a-radio>
					</a-radio-group>
				</div>
			</a-col>
			<a-col :span="10" :offset="2">
				<div>
					<span style="margin-right: 5px">战略合作商:</span>
					<a-checkbox v-model:checked="copperation"></a-checkbox>
				</div>
			</a-col>
		</a-row>
		<CompanyForm ref="companyRef" v-show="supplierEntity == 1" style="margin-top: 12px" />
		<PersonalForm ref="personalRef" v-show="supplierEntity == 2" style="margin-top: 12px" />
		<div style="margin-top: 12px">
			<span style="margin-right: 13px">账户信息:</span>
			<a-button type="primary" class="childAddButton" @click="addBankInformation()">
				<PlusOutlined />
				新增
			</a-button>
			<a-popconfirm title="是否删除?" @confirm="removeBankInformation()">
				<a-button style="margin-left: 12px" type="remove" danger>
					<LineOutlined />
					删除</a-button
				>
			</a-popconfirm>
		</div>
		<a-row>
			<a-col :span="24">
				<a-table
					:row-selection="options.rowSelection"
					:pagination="false"
					:columns="columns"
					:data-source="accountList"
				>
					<template #emptyText>
						<span>添加开户行信息</span>
					</template>
					<template #bodyCell="{ column, index, record }">
						<template v-if="column.dataIndex === 'index'">
							<span>{{ index + 1 }}</span>
						</template>

						<template v-if="column.dataIndex === 'main'">
							<div class="editable-cell">
								<a-checkbox @change="(v) => onCheckChange(v, record)" v-model:checked="record.main"></a-checkbox>
							</div>
						</template>
						<template v-if="column.dataIndex === 'name'">
							<div class="editable-cell">
								<a-input v-model:value="record.name" />
							</div>
						</template>
						<template v-if="column.dataIndex === 'bank'">
							<div class="editable-cell">
								<a-input v-model:value="record.bank" />
							</div>
						</template>
						<template v-if="column.dataIndex === 'account'">
							<div class="editable-cell">
								<a-input v-model:value="record.account" />
							</div>
						</template>
						<template v-if="column.dataIndex === 'remark'">
							<div class="editable-cell">
								<a-input v-model:value="record.remark" />
							</div>
						</template>
					</template>
				</a-table>
			</a-col>
		</a-row>
		<template #footer>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
		</template>
	</xn-form-container>
</template>

<script setup name="supplierForm">
	import { message } from 'ant-design-vue'
	import CompanyForm from './companyForm.vue'
	import PersonalForm from './personalForm.vue'
	import supplierApi from '@/api/base_data/supplierApi'
	import tool from '@/utils/tool'
	const personalRef = ref()
	const title = ref('新增')
	const companyRef = ref()
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const supplierEntity = ref(1)
	const accountList = ref([])
	const copperation = ref(false)
	const submitLoading = ref(false)
	const detail = ref(null)
	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	const onCheckChange = (change, record) => {
		let checked = change.target.checked
		let accounts = accountList.value
		accounts.forEach((it) => {
			if (it.key != record.key) {
				it.main = false
			}
		})
		record.main = true
	}
	const addBankInformation = () => {
		accountList.value.push({
			key: tool.snowyUuid(),
			remark: '',
			name: '',
			bank: '',
			account: ''
		})
	}
	const removeBankInformation = () => {
		let datas = accountList.value
		if (!datas || datas.length <= 0) {
			message.error('请选择账户信息!')
			return
		}
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['key'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})
		selectedRowKeys.value = []
	}

	const selectedRowKeys = ref([])
	// 打开抽屉
	const onOpen = (record) => {
		title.value = '新增'
		detail.value = null
		supplierEntity.value = '1'
		copperation.value = false
		visible.value = true
		accountList.value = []
		if (record) {
			title.value = '编辑'
			loadDetail(record.id)
		}
	}

	const loadDetail = (id) => {
		supplierApi
			.getDetail({ id })
			.then((value) => {
				detail.value = value
				accountList.value = value.accountList.map((element) => {
					element['key'] = element['id']
					return element
				})
				let commonParams = {
					head: value.head,
					platform: value.platform,
					remark: value.remark,
					purchaseSite: value.purchaseSite,
					mainRange: value.mainRange,
					onlinePurchase: value.onlinePurchase == 1
				}
				if (value.supplierEntity == 1) {
					value.contactsList = value.contactsList.map((element) => {
						element['key'] = element['id']
						return element
					})
					companyRef.value.setFormValue(value)
					personalRef.value.setFormValue(commonParams)
				} else {
					personalRef.value.setFormValue(value)
					companyRef.value.setFormValue(commonParams)
				}
				supplierEntity.value = value.supplierEntity
				copperation.value = value.copperation == 1
			})
			.catch(() => {})
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}
	const columns = [
		{
			title: '序号',
			dataIndex: 'index',
			align: 'center',
			width: 80
		},
		{
			title: '是否主账号',
			dataIndex: 'main',
			align: 'center',
			width: 110
		},
		{
			title: '户名',
			dataIndex: 'name',
			align: 'center'
		},
		{
			title: '开户行',
			dataIndex: 'bank',
			align: 'center'
		},
		{
			title: '账号',
			dataIndex: 'account',
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			align: 'center'
		}
	]
	const validateAccount = () => {
		const banks = accountList.value
		if (!banks || banks.length <= 0) {
			message.error('请添加账户信息!')
			return false
		}
		for (let i = 0; i < banks.length; i++) {
			let it = banks[i]
			if (!it.name) {
				message.error(`第${i + 1}行户名不能为空!`)
				return false
			}
			if (!it.bank) {
				message.error(`第${i + 1}行开户行不能为空!`)
				return false
			}
			if (!it.account) {
				message.error(`第${i + 1}行手账号不能为空!`)
				return false
			}
		}
		let main = false
		for (let it of banks) {
			if (it.main) {
				main = true
				break
			}
		}
		if (!main) {
			message.error('请选择主账号')
			return false
		}
		return true
	}
	// 验证并提交数据
	const onSubmit = () => {
		let promise = supplierEntity.value == 1 ? companyRef.value.validate() : personalRef.value.validate()
		let params =
			supplierEntity.value == 1 ? Object.assign(companyRef.value.formData) : Object.assign(personalRef.value.formData)
		params.onlinePurchase = params.onlinePurchase ? 1 : 0
		promise
			.then(() => {
				if (validateAccount()) {
					submitLoading.value = true
					let id = detail.value ? detail.value.id : null
					supplierApi
						.addOrEdit(
							detail.value ? 'edit' : 'add',
							Object.assign(params, {
								supplierEntity: supplierEntity.value,
								copperation: copperation.value ? 1 : 0,
								id,
								accountList: accountList.value
							})
						)
						.then(() => {
							visible.value = false
							emit('successful')
						})
						.finally(() => {
							submitLoading.value = false
						})
				}
			})
			.catch((e) => {
				console.log(e)
			})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
